//
//  IDCardViewController.m
//  SecondLoan
//
//  Created by 姚永波 on 2019/8/20.
//  Copyright © 2019 姚永波. All rights reserved.
//

#import "IDCardViewController.h"
#import "UIImage+Stretch.h"
#import "YSHYClipViewController.h"
#import "FormData.h"
#import "NSString+Tools.h"
#import "IDFaceViewController.h"
#import "SDRecImagePickerController.h"
#import "CustomCameraViewController.h"
#import "UIImage+Rotation.h"
#import "UIImage+Stretch.h"


@interface IDCardViewController ()<UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,CustomCameraDelegate>
{
    NSInteger _currentSelectedIndex;
}
@property (weak, nonatomic) IBOutlet UIButton *btnIDUpFace;
@property (weak, nonatomic) IBOutlet UIButton *btnIDDownFace;

@property (weak, nonatomic) IBOutlet UIImageView *upImageView;
@property (weak, nonatomic) IBOutlet UIImageView *downImageView;


@property (strong, nonatomic) NSData *imgUpData;
@property (strong, nonatomic) NSData *imgDownData;

@property (weak, nonatomic) IBOutlet UITextField *tfName;
@property (weak, nonatomic) IBOutlet UITextField *tfIDnumber;
@property (weak, nonatomic) IBOutlet UIButton *btnNext;

@end

@implementation IDCardViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"完善身份信息";
    [self setupViews];
}

- (void)setupViews{
    _upImageView.hidden = YES;
    _downImageView.hidden = YES;
    [_upImageView setContentMode:UIViewContentModeScaleAspectFill];
    [_upImageView.layer setCornerRadius:5.];
    [_upImageView.layer setMasksToBounds:YES];
    [_downImageView setContentMode:UIViewContentModeScaleAspectFill];
    [_downImageView.layer setCornerRadius:5.];
    [_downImageView.layer setMasksToBounds:YES];
    _btnNext.enabled = NO;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}
//- (void)setModel:(UserModel *)model
//{
//    _model = model;
//    if (model.idcard_positive.length) {
//        _upImageView.hidden = NO;
//        _downImageView.hidden = NO;
//        [_upImageView sd_setImageWithURL:[NSURL URLWithString:model.idcard_positive] placeholderImage:nil];
//        [_downImageView sd_setImageWithURL:[NSURL URLWithString:model.idcard_opposite] placeholderImage:nil];
//    }else{
//
//    }
//}
- (IBAction)nextAction:(UIButton *)sender {
//    if (!_tfName.text.length) {
//        WKBToastInfo(MsgHintNameEmpty);
//        return;
//    }else if (![_tfName.text validateEightChineseCharater]){
//        WKBToastInfo(MsgHintNameNoCorrect);
//        return;
//    }
//
//    if (!_tfIDnumber.text.length) {
//        WKBToastInfo(MsgHintIDCardEmpty);
//        return;
//    }else{
//        if (![_tfIDnumber.text validateIdentityCard]) {
//            WKBToastInfo(MsgHintIDCardNoCorrect);
//            return;
//        }
//    }
    if (!_tfName.text.length || !_tfIDnumber.text.length || ![_tfIDnumber.text validateIdentityCard]) {
        WKBToastInfo(MsgHintIDCardNoCorrect);
        return;
    }
    IDFaceViewController *idFaceVC = [[IDFaceViewController alloc] initWithNibName:@"IDFaceViewController" bundle:nil];
    idFaceVC.isOnlyAuth = self.isOnlyAuth;
    idFaceVC.productId = self.productId;
    idFaceVC.name = self.tfName.text;
    idFaceVC.idCard = self.tfIDnumber.text;
    [self.navigationController pushViewController:idFaceVC animated:YES];
}


- (IBAction)openCameraAction:(UIButton *)sender {
    _currentSelectedIndex = sender.tag;
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照上传",@"本地上传", nil];
    [sheet showInView: self.view];
}

#pragma mark UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
       switch (buttonIndex) {
        case 2 :
            return;
            break;
        case 0:
           {
               CustomCameraViewController *pickController = [[CustomCameraViewController alloc] init];
               pickController.delegate = self;
               pickController.isCard = YES;
               [self presentViewController:pickController animated:YES completion:nil];
           }
            break;
        case 1:
           {
               if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) return;
               UIImagePickerController *pickController = [[UIImagePickerController alloc] init];
               pickController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
               pickController.delegate = self;
               if ([pickController.navigationBar respondsToSelector:@selector(setBarTintColor:)]) {
                   [[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:COLOR_ThemeRed,
                                                                          NSFontAttributeName:[UIFont systemFontOfSize:18]}];
                   [[UINavigationBar appearance] setTranslucent:NO];
                   [[UINavigationBar appearance] setTintColor:COLOR_ThemeRed];
               }
               [self presentViewController:pickController animated:YES completion:nil];
           }
            break;
    }
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor],
                                                           NSFontAttributeName:[UIFont systemFontOfSize:18]}];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor],
                                                           NSFontAttributeName:[UIFont systemFontOfSize:18]}];
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    [self ClipViewController:nil FinishClipImage:image];
}

- (void)imageCameraController:(CustomCameraViewController *)picker didFinishPickingMediaWithImage:(UIImage *)image
{
    [self ClipViewController:nil FinishClipImage:image];
}

#pragma mark - ClipViewControllerDelegate
-(void)ClipViewController:(YSHYClipViewController *)clipViewController FinishClipImage:(UIImage *)editImage {
    UIImage *image = editImage;
    CGFloat expectWidth  = 0.;
    CGFloat expectHeight = 0;
    if (image.size.width > image.size.height) {
        expectWidth = 800;
        CGFloat imageWidth  = image.size.width;
        expectHeight= expectWidth / imageWidth * image.size.height;
    }else{
        expectHeight = 800;
        CGFloat imageHeight  = image.size.height;
        expectWidth = expectHeight / imageHeight * image.size.width;
    }
    CGSize expectSize = CGSizeMake(expectWidth, expectHeight);
    UIImage *resizeImage = [image scaleToSize:expectSize];
//    NSData *imageData = UIImageJPEGRepresentation(image, .8);
    NSData *imageData = UIImageJPEGRepresentation(resizeImage, .8);
    if (image) {
         if (_currentSelectedIndex == 0) {
             self.imgUpData = imageData;
             _upImageView.hidden = NO;
             _upImageView.image = image ;
         }else{
             self.imgDownData = imageData;
             _downImageView.hidden = NO;
             _downImageView.image = image;
         }
        if (self.imgUpData != nil && self.imgDownData != nil) {
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            hud.label.text = @"上传中";
            NSMutableDictionary * param = [NSMutableDictionary dictionary];
            [param setObject:[UserLocal token] forKey:@"token"];
            //             NSData *imgUpData = UIImageJPEGRepresentation(_upImageView.image, .8);
            NSString *encodedUp= [self.imgUpData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
            //             NSData *imgDownData = UIImageJPEGRepresentation(_downImageView.image, .8);
            NSString *encodedDown= [self.imgDownData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
            [param setObject:@[
                               @{
                                   @"type":@"1",
                                   @"pic":encodedUp
                                   },
                               @{
                                   @"type":@"2",
                                   @"pic":encodedDown
                                   }
                               ] forKey:@"idCardInfo"];
            WeakSelf
            [[PLRequestManage sharedInstance] httpRequestWithUrl:HTTPAPIWITH(url_getCardInfo) Type:RequestPost parameters:param completeHandle:^(id  _Nullable responseObject, NSError *error) {
                [hud hideAnimated:YES];
                if (!error) {
                    if (responseObject[@"data"]) {
                        NSDictionary *dicData = responseObject[@"data"];
                        weakSelf.tfName.text = dicData[@"name"];
                        weakSelf.tfIDnumber.text = dicData[@"idcard"];
                        if (weakSelf.tfIDnumber.text.length > 0) {
                            [self HUDshowSuccessWithStatus:@"识别成功"];
                            weakSelf.btnNext.enabled = YES;
                        }else{
                            [self HUDshowSuccessWithStatus:@"识别失败"];
                        }
                    }
                } else {
                    NSDictionary *result = responseObject;
                    @try {// 可能会出现崩溃的代码
                        if ([result containsObjectForKey:@"status"]) {
                            NSInteger status = [result[@"status"] integerValue];
                            if (status == 2 || status == 3) { //身份证正面信息失败
                                [self HUDshowErrorWithStatus:error.localizedDescription];
                                weakSelf.imgUpData = nil;
                            }else if(status == 5 || status == 6 ){ //身份证背面信息失败
                                [self HUDshowErrorWithStatus:error.localizedDescription];
                                weakSelf.imgDownData = nil;
                            }else{
                                weakSelf.imgUpData = nil;
                                weakSelf.imgDownData = nil;
                                [self HUDshowErrorWithStatus:error.localizedDescription];
                            }
                        }else{
                            [self HUDshowSuccessWithStatus:@"识别失败"];
                        }
                    }
                    @catch (NSException *exception) {
                        // 捕获到的异常exception
                        weakSelf.imgUpData = nil;
                        weakSelf.imgDownData = nil;
                        [self HUDshowSuccessWithStatus:@"识别失败"];
                    }
                    
                }
            }];
        }
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}



@end
